
String.prototype.formatNumber = function(thousandSeparator, decimals) {
    var startIndex, output = '', thisStr = this, str = '', addDash = false, decimalSeparator;

    if ('.' === thousandSeparator) {
        decimalSeparator = ',';
    } else {
        decimalSeparator = '.';
    }

    if (null === decimals || undefined === decimals) {
        decimals = 0;
    }

    if (decimals > 0) {
        var bridgeNum = 1;
        for (var i = 1; i <= decimals; i++) {
            bridgeNum *= 10;
        }
        thisStr = Math.round(thisStr*bridgeNum)/bridgeNum + '';
    }

    if ('-' == thisStr.charAt(0)) {
        addDash = true;
        str = thisStr.substring(1).replace(new RegExp('[^0-9' + decimalSeparator.replace('.', '\\.') + '%]', 'g'), '');
    } else {
        str = thisStr.replace(new RegExp('[^0-9' + decimalSeparator.replace('.', '\\.') + '%]', 'g'), '');
    }

    var dotPos = str.indexOf(decimalSeparator);
    var pcPos = str.indexOf('%');
    if (dotPos > -1) {
        startIndex = dotPos - 1;
        output = str.substr(dotPos);
    } else if (pcPos > -1) {
        startIndex = pcPos - 1;
        output = str.substr(pcPos);
    } else {
        startIndex = str.length - 1;
    }
    var charCounter = 0;
    for (i = startIndex; i >= 0; i--) {
        charCounter++;
        output = str.charAt(i) + output;
        if (charCounter%3===0 && i > 0) {
            output = thousandSeparator + output;
        }
    }
    if (addDash) {
        output = '-' + output;
    }
    return output;
};

String.prototype.removeNumberFormat = function(thousandSeparator) {
    return this.replace(new RegExp(thousandSeparator.replace('.', '\\.') + '+', 'g'), '');
};